var app=getApp()
var openid=wx.getStorageSync('openid')


Page({

  /**
   * 页面的初始数据
   */
  data: {
    credit:'',
    lottery:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.refresh()
  },
  refresh(){
    wx.cloud.callFunction({
      name:'getClientData',
    })
    .then(res=>{
       let credit=res.result.data[0].credit
       let lottery=res.result.data[0].lotteryTimes
      this.setData({
        credit:credit,
        lottery:lottery
      })
    })
   },
  async convert(){
    var select=null
    wx.showActionSheet({
      itemList: ['300积分兑换1次', '500积分兑换2次'],
    })
    .then(res=>{console.log(res.tapIndex);select=res.tapIndex})
    .then(res=>{if(select==0)
                {
                  if(this.data.credit>=300){
                    wx.cloud.callFunction({
                    name:'Convert',
                    data:{reduceCredit:300,
                          addlottery:1,
                          }
                  }).then(()=>{this.refresh()})
                    
                  }
                  else{
                    wx.showToast({
                      title: '积分不足',
                      icon:'none'
                    }).then(()=>{return})
                    .catch(()=>{console.log("出错");})
                  } 
                }
                else{
                  if(this.data.credit>=500)
                  { wx.cloud.callFunction({
                    name:'Convert',
                    data:{reduceCredit:500,
                          addlottery:2,
                          }
                  }).then(res=>{this.refresh()})
                }
                  else{wx.showToast({
                    title: '积分不足',
                    icon:'none'
                  }).then(()=>{return})
                  .catch(()=>{console.log("出错");})}
                 
                }
              })
    .catch(res=>{console.log(res.errMsg);})
  },
  async luckyDrawBox(){
    let times= await wx.cloud.callFunction({
      name:"getClientData"
    })
   let lotterytimes=times.result.data[0].lotteryTimes
    if(lotterytimes>0){
      wx.cloud.callFunction({
        name:"Lottery"
      })
      .then(res=>{
        console.log("成功",res.result.prize.data[0].prize);
        this.refresh()
      })
      .catch(res=>{
        console.log(res);
      })
    }
    else{
      wx.showToast({
        title: '抽奖次数不足，请先兑换',
        icon:"none"
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.refresh()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})